var listPage = avalon.define({
    $id: "listPage",
    layout: true,
    cid: 1,
    noProductData: "",
    subCategoryId: "",
    checked: {},
    isChecked: function(value) {
        var checked = listPage.checked;
        if (null != checked[value]) {
            return true;
        } else {
            return false;
        }
    },
    data: {
        childs: [],
        isSmall: 0,
        categorys: [],
        parent: {
            name: ""
        },
        facets: []
    },
    getFacets: function(cid, type) {
        mui.ajax('/product/facet.json', {
            data: { cid: cid, type: type },
            dataType: 'json',
            type: "post",
            success: function(data) {
                listPage.data.facets = data.facets;
                //1:获取筛选项 0：根据下拉框获取筛选项
                if (1 == type) {
                    listPage.data.parent = data.parent;
                    listPage.data.isSmall = data.parent.isSmall;

                    if (1 == listPage.data.isSmall) {
                        listPage.data.categorys = data.childs;
                        //选中下拉框
                        listPage.subCategoryId = window.localStorage.getItem('dahua_sid');
                        listPage.chooseCategory();
                    }

                    //控制filter的显示
                    // if (data.facets.length > 0 || 1 == listPage.data.isSmall) {
                    //     if (!$(".filterBtn").hasClass("filter")) {
                    //         $(".filterBtn").addClass("filter")
                    //     }
                    // } else {
                    //     $(".filter-bar").addClass("mui-hidden");
                    //     $("#productList").removeClass("mt91");
                    //     $(".mui-pull-top-pocket").css("top", "44px");
                    // }
                }

            }
        });
    },
    chooseCategory: function() {
        var subCategoryId = listPage.subCategoryId;
        listPage.data.facets = [];
        if (subCategoryId) {
            listPage.getFacets(subCategoryId, 0);
        }
    },
    //重置搜索条件
    resetFacetFields: function() {
        window.localStorage.setItem('dahua_facets', "");
        listPage.checked = {};
        window.localStorage.setItem('dahua_sid', "");

        if (1 == listPage.data.isSmall) {
            listPage.data.facets = [];
            listPage.subCategoryId = "";
        }

    },
    //保存搜索条件
    saveFacetFields: function(facets) {
        window.localStorage.setItem('dahua_facets', JSON.stringify(facets));
    },
    //保存搜索条件
    saveFacetSid: function(sid) {
        window.localStorage.setItem('dahua_sid', sid);
    },
    //保存搜索条件
    saveFacetCid: function(cid) {
        window.localStorage.setItem('dahua_cid', cid);
    },
    //获取搜索条件
    getFacetFields: function() {
        var data = window.localStorage.getItem("dahua_facets");
        if ("" == data || null == data) {
            return {};
        } else {
            return JSON.parse(data);
        }
    },
    compare: {
        btnText: "Product Comparison",
        values: [],
        max: 9,
        selected: function(id) {
            var icheckbox = $('#' + id);
            if ($(".compareBtn").hasClass("compared")) {
                var max = this.max;
                var values = this.values;
                if (icheckbox.is(':checked')) {
                    if (values.length + 1 > max) {
                        $(icheckbox).attr("checked", false);
                        mui.toast("You can choose " + max + " products at most");
                    } else {
                        values.push(id);
                        this.btnText = "Complete(" + values.length + "/" + max + ")";
                        this.values = values;
                    }

                } else {
                    var tmpValues = [];
                    avalon.each(values, function(i, value) {
                        if (id != value) {
                            tmpValues.push(value);
                        }
                    });
                    this.values = tmpValues;
                    this.btnText = "Complete(" + tmpValues.length + "/" + max + ")";
                }
            } else {
                $(icheckbox).attr("checked", false);
                var url = "pdp.html?id=" + id;
                mui.openWindow({
                    url: url
                });
            }

        }
    }
});


mui.ready(function() {
    var filterCanvasWrapper = mui('#filterCanvasWrapper');
    mui(".filter-bar").on('tap', '.filterBtn', function() {
        // filterCanvasWrapper.offCanvas('show');
        var url = this.getAttribute('href');
        mui.openWindow({
            url: url
        });
        sessionStorage.setItem('todo', 2)
    });
    var cid = $.getParameter("cid");
    // listPage.checked = listPage.getFacetFields();
    listPage.saveFacetCid(cid);

    listPage.cid = cid;
    listPage.getFacets(listPage.cid, 1);


    mui.init({
        gestureConfig: {
            tap: true, //默认为true 
            doubletap: true, //默认为false 
            longtap: true
        },
        pullRefresh: {
            container: "#productList",
            down: {
                height: 50,
                auto: true,
                contentdown: $.i18n.contentDown,
                contentover: $.i18n.contentOver,
                contentrefresh: $.i18n.contentRefresh,
                callback: function() {

                    $(".getMore").show();
                    listPage.noProductData = "";
                    setTimeout(function() {
                        var facetForm = $("#facetForm").serialize();
                        mui.ajax('/product/list.json', {
                            data: facetForm,
                            dataType: 'json',
                            type: "post",
                            success: function(data) {
                                listPage.data.childs = data.childs;
                                var count = 0;
                                avalon.each(data.childs, function(i, item) {
                                    var products = item.products;
                                    if (products != undefined) {
                                        count = count + products.length;
                                    }
                                });
                                if (0 == count) {
                                    listPage.noProductData = "<img src='../../resources/images/noDataImg.png'><p>No data</p>";
                                    $(".compareBtn").addClass("mui-hidden");
                                } else {
                                    $(".compareBtn").removeClass("mui-hidden");
                                }
                                mui('#productList').pullRefresh().endPulldownToRefresh();
                            }
                        });
                    }, window.DAHUA_CONFIG.LOADING_TIME);
                }
            }
        }
    });

    //layout布局
    mui(".mui-bar-nav").on('tap', '.layout', function() {
        var layout = listPage.layout;
        if (layout) {
            listPage.layout = false;
        } else {
            listPage.layout = true;
        }
    });

    //reset按钮
    mui(".filter-btn").on('tap', '.resetBtn', function() {
        listPage.noProductData = "";
        listPage.resetFacetFields();

        $('#facetForm')[0].reset();
        listPage.cid = listPage.cid;
        $(".getMore").show();

        mui.ajax('/product/list.json', {
            data: { cid: listPage.cid },
            type: "post",
            dataType: 'json',
            success: function(data) {
                listPage.data.childs = data.childs;
                var count = 0;
                avalon.each(data.childs, function(i, item) {
                    var products = item.products;
                    if (products != undefined) {
                        count = count + products.length;
                    }
                });
                if (0 == count) {
                    listPage.noProductData = "<img src='../../resources/images/noDataImg.png'><p>No data</p>";
                    $(".compareBtn").addClass("mui-hidden");
                } else {
                    $(".compareBtn").removeClass("mui-hidden");
                    mui('#productList').scroll().scrollTo(0, 0, 100);
                }
                mui('.mui-off-canvas-wrap').offCanvas('show');
            }
        });

    });
    //搜索按钮
    mui(".filter-btn").on('tap', '.searchBtn', function() {
        listPage.noProductData = "";
        $(".getMore").show();
        var facetForm = $("#facetForm").serialize();
        mui.ajax('/product/list.json', {
            data: facetForm,
            type: "post",
            dataType: 'json',
            success: function(data) {
                mui('.mui-off-canvas-wrap').offCanvas('show');

                listPage.data.childs = data.childs;
                var count = 0;
                avalon.each(data.childs, function(i, item) {
                    var products = item.products;
                    if (products != undefined) {
                        count = count + products.length;
                    }
                });
                if (0 == count) {
                    listPage.noProductData = "<img src='../../resources/images/noDataImg.png'><p>No data</p>";
                    $(".compareBtn").addClass("mui-hidden");
                } else {
                    mui('#productList').scroll().scrollTo(0, 0, 100);
                    $(".compareBtn").removeClass("mui-hidden");
                }

                //保存查询条件
                listPage.checked = data.checked;
                listPage.saveFacetFields(data.checked);
                listPage.saveFacetSid(listPage.subCategoryId);
            }
        });
    });

    //search按钮
    mui(".mui-bar-nav").on('tap', '.search', function() {
        var url = this.getAttribute('href');
        mui.openWindow({
            url: url
        });
    });

    //点击开始比较按钮
    mui(".filter-bar").on('tap', '.startCompare', function() {
        listPage.compare.btnText = "Complete";
        //隐藏不需要比较的类目
        if (1 == listPage.data.isSmall) {
            // $(".catItems").addClass("mui-hidden");
            avalon.each(listPage.data.categorys, function(i, category) {
                $("#" + category.id).removeClass("mui-hidden");
            });
        }
        if ($(".icheckbox").hasClass("mui-hidden")) {
            $(".icheckbox").removeClass("mui-hidden");
        }
        if (!$(".product").hasClass("mui-checkbox")) {
            $(".product").addClass("mui-checkbox");
        }

        if (!$(".compareBtn").hasClass("compared")) {
            $(".compareBtn").addClass("compared");
        }
        if ($(".compareBtn").hasClass("startCompare")) {
            $(".compareBtn").removeClass("startCompare");
        }
    });

    //跳转到比较页面
    mui(".filter-bar").on('tap', '.compared', function() {
        var values = listPage.compare.values;
        if (values.length == 0) {
            listPage.compare.btnText = "Product Comparison";
            $(".icheckbox").addClass("mui-hidden");
            $(".compareBtn").addClass("startCompare");
            $(".compareBtn").removeClass("compared");
            if (1 == listPage.data.isSmall) {
                $(".catItems").removeClass("mui-hidden");
            }

        } else if (values.length == 1) {
            mui.toast('Select two products at least');
        } else {
            var url = "compare.html";
            mui.openWindow({
                url: url + "?id=" + values
            });
        }
    });


    //获取更多商品
    mui("#productList").on('tap', '.getMore', function() {
        var id = this.getAttribute('data-id');
        var facetForm = $("#facetForm").serialize();
        mui.ajax("/product/more.json?id=" + id, {
            data: facetForm,
            dataType: 'json',
            type: "post",
            success: function(data) {
                for (var i = 0; i < listPage.data.childs.length; i++) {
                    if (id == listPage.data.childs[i].id) {
                        var products = listPage.data.childs[i].products;
                        products.push.apply(products, data.products);
                        listPage.data.childs[i].products = products;
                    }
                }
                $("#cat" + id).hide();

                if ($(".compareBtn").hasClass("compared")) {
                    $(".icheckbox").removeClass("mui-hidden");
                    $(".product").addClass("mui-checkbox");
                }
            }
        });
    });

});